//
//  LGAFNetWork.m
//  UniverseProject
//
//  Created by ETOP on 2018/2/25.
//  Copyright © 2018年 Cloud2209. All rights reserved.
//


#import <AFNetworking.h>
#import "LGAFNetWork.h"

@implementation LGAFNetWork


/// POST请求
/// @param url 请求地址
/// @param params 参数 ps  如果参数包含键 NEED_TOKEN 那么请求头会自动携带token
/// @param success 成功回调
/// @param fail 失败回调
+(void)POST:(NSString *)url params:(NSDictionary *)params
    success:(LGResponseSuccess)success fail:(LGResponseFail)fail{
    AFHTTPSessionManager *manager = [LGAFNetWork managerWithBaseURL:nil sessionConfiguration:NO];
    NSDictionary *headers;
    if ([params jk_hasKey:NEED_TOKEN]) {
        NSString *token = [LGCache getStringRecordByKey:CURRENT_TOKEN];
        headers = [NSDictionary dictionaryWithObject:token forKey:CURRENT_TOKEN];
    }
    
    [manager POST:NETWORK(url) parameters:params  headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        ReqSuccessInfo *successInfo = [ReqSuccessInfo mj_objectWithKeyValues:responseObject];
        success(task,successInfo);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *erroInfo = error.userInfo;
        NSData *data = [erroInfo valueForKey:@"com.alamofire.serialization.response.error.data"];
        NSString *errorString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *resultDict = [NSString dictionaryWithJsonString:errorString];
        ReqErrorInfo *errorModel = [ReqErrorInfo mj_objectWithKeyValues:resultDict];
        fail(task,errorModel);
    }];
}


#pragma mark - Private

+(AFHTTPSessionManager *)managerWithBaseURL:(NSString *)baseURL  sessionConfiguration:(BOOL)isconfiguration{
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager =nil;
    
    NSURL *url = [NSURL URLWithString:baseURL];
    
    if (isconfiguration) {
        
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
    }else{
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
    }
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    return manager;
}


@end


